/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.coffeemaker.application.commands;

import com.nanosn.coffeemaker.Project;
import com.nanosn.util.parsers.commandline.Command;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author selkhateeb
 */
public class Compile implements Command {

    public void run(String[] args) throws Exception {
        /*
         * 1. Collect all java files
         * 2. Complie them
         */

        List<String> filesToCompile = getAllJavaFilesInDirectory(new File(
                Project.getDevelopmentDirectory()));
        compile(filesToCompile);

    }

    public void compile(List<String> filesToCompile) throws Exception {

        ArrayList<String> args = new ArrayList<String>();
//        args.add("-version");
        args.addAll(filesToCompile);

        int compile = com.sun.tools.javac.Main.compile(args.toArray(
                new String[args.size()]));
        if (compile != 0) {
            throw new Exception("Compiler Error");
        }
    }

    public String getHelp() {
        return "Compiles all java files";
    }

    public List<String> getAllJavaFilesInDirectory(File dir) {
        List<String> files = new ArrayList<String>();

        for (File file : dir.listFiles()) {
            if (file.isFile() && file.getAbsolutePath().endsWith(".java")) {
                if (!file.getAbsolutePath().contains("GWT")) {
                    files.add(file.getAbsolutePath());
                }
            }
            else if (file.isDirectory()) {
                files.addAll(getAllJavaFilesInDirectory(file));
            }
        }
        return files;
    }
}
